import 'package:flutter/material.dart';

typedef void OnTap(Header name);

class ScrollTabHeader extends StatefulWidget {
  ///[Widget]所在可滚动的视图控制器
  final ScrollController scrollController;

  ///滚动默认高度
  final double defaultHeight;

  /// 下划线颜色
  final Color underLineColor;

  ///字体颜色
  final Color fontColor;

  ///选中后字体颜色
  final Color selectedFontColor;

  ///背景颜色，默认白色
  final Color backgroundColor;

  ///点击事件
  final OnTap onTap;

  ///默认选中的头部索引
  final int defaultSelectedHeaderIndex;

  ///滚动头信息
  final List<Header> headerNames;

  final Padding padding;

  final GlobalKey safeAreaKey;
  const ScrollTabHeader({
    Key key,
    this.scrollController,
    this.headerNames,
    this.onTap,
    this.underLineColor = Colors.red,
    this.defaultHeight = 0,
    this.backgroundColor = Colors.white,
    this.fontColor = Colors.black,
    this.selectedFontColor = Colors.red,
    this.defaultSelectedHeaderIndex,
    this.padding,
    this.safeAreaKey,
  }) : super(key: key);

  @override
  _ScrollTabHeaderState createState() => _ScrollTabHeaderState();
}

class _ScrollTabHeaderState extends State<ScrollTabHeader> {
  int selectedHeaderIndex;
  @override
  void initState() {
    selectedHeaderIndex = this.widget.defaultSelectedHeaderIndex;
    this.widget.scrollController.addListener(() {
      //(this.widget.scrollController.offset);
      //监听滚动位置设置tab样式
      for (int index = 0; index < this.widget.headerNames.length; index++) {
        RenderBox box = this
            .widget
            .headerNames[index]
            .targetKey
            .currentContext
            .findRenderObject();
        double safeAreaTop =
            MediaQuery.of(this.widget.safeAreaKey?.currentContext).padding.top;
        if (box.localToGlobal(Offset.zero).dy - safeAreaTop-30 <=
            this.widget.defaultHeight) {
          setState(() {
            selectedHeaderIndex = index;
          });
        }
      }
    });
    super.initState();
  }

  void onTap(int index) {
     if (index == 0) {
        this.widget.scrollController.animateTo(0,
            duration: Duration(milliseconds: 600),
            curve: Curves.easeInOutQuint);
        return;
      }
      //滚动指定位置
      RenderBox box = this
          .widget
          .headerNames[index]
          .targetKey
          .currentContext
          .findRenderObject();

      double dy = box.localToGlobal(Offset(0, 0)).dy;
      double safeAreaTop =
          MediaQuery.of(this.widget.safeAreaKey?.currentContext).padding.top;

      double scrollOffset = this.widget.scrollController.offset +
          dy -
          this.widget.defaultHeight -
          safeAreaTop;
      this.widget.scrollController.animateTo(scrollOffset,
          duration: Duration(milliseconds: 500), curve: Curves.bounceInOut);
    if (this.widget.onTap != null) {
      this.widget.onTap(this.widget.headerNames[index]);
    }
  }

  @override
  Widget build(BuildContext context) {
    //print("this.widget.defaultHeight:${this.widget.defaultHeight}");
    List<Widget> headerWidgetNames = [];
    for (int index = 0; index < this.widget.headerNames.length; index++) {
      if (this.selectedHeaderIndex == index) {
        headerWidgetNames.add(TabName(
            index: index,
            isSelected: true,
            header: this.widget.headerNames[index],
            onTap: this.onTap));
      } else {
        headerWidgetNames.add(TabName(
            index: index,
            header: this.widget.headerNames[index],
            onTap: this.onTap));
      }
    }

    return Container(
      color: this.widget.backgroundColor,
      padding: this.widget.padding == null
          ? const EdgeInsets.all(5)
          : this.widget.padding,
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: headerWidgetNames),
    );
  }
}

///头部信息
class Header {
  ///头部保存的数据
  final Object data;

  ///名称
  final String name;

  ///滚动到目标的[Widget]的Key
  final GlobalKey targetKey;

  Header({@required this.name, @required this.targetKey, this.data});
}

typedef void TabNameOnTap(int index);

class TabName extends StatelessWidget {
  final Header header;
  final Color fontColor;
  final Color selectedColor;
  final bool isSelected;
  final TabNameOnTap onTap;
  final int index;
  const TabName(
      {Key key,
      @required this.header,
      this.fontColor = Colors.black,
      this.onTap,
      this.selectedColor = Colors.red,
      this.isSelected = false,
      this.index = 0})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap != null
          ? () {
              onTap(this.index);
            }
          : null,
      child: Column(
        children: <Widget>[
          Text(
            this.header.name,
            style:
                TextStyle(color: this.isSelected ? selectedColor : fontColor),
          ),
          SizedBox(
            height: 3,
          ),
          AnimatedContainer(
            height: 2,
            width: 30,
            decoration: BoxDecoration(
                color:
                    this.isSelected ? this.selectedColor : Colors.transparent,
                borderRadius: BorderRadius.circular(5)),
            duration: Duration(milliseconds: 300),
          )
        ],
      ),
    );
  }
}
